01 / 04

How does the testing package support table-driven tests and benchmarks?

Table-driven tests use a slice of test cases iterated with t.Run() for isolated subtests. Benchmarks use the testing.B type with a b.N loop that the runtime calibrates automatically.

Table-driven tests and benchmarks
Testing best practices
  1. 1

    t.Run() creates isolated subtests — failures are reported individually and can be run in parallel with t.Parallel()

  2. 2

    Use testify/assert for cleaner assertion messages: assert.Equal(t, expected, actual)

  3. 3

    b.ResetTimer() to exclude setup time from benchmark measurements

  4. 4

    go test -race -count=10 catches non-deterministic race conditions

  5. 5

    Examples (func ExampleXxx) serve as documentation and are verified by go test